# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError
from common.utils.qr import make_code

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '289880000001': {
        #  秒付 支付宝扫码红包 2.8% 10-10000 dwc
        'API_KEY': '5DA17C0EC9C2469A99DC30316D3EDB8B',
        'gateway': 'http://channel.uranuspay.com/agent/transReq.action',
        'query_gateway': 'http://qry.uranuspay.com/onlinepayQry/gateway.action',
        'ip': '103.71.50.181',
        # 'ip': '219.135.56.195'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_production_ip(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("miaofupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay_scan':
        return '0010'
    elif service == 'alipay_h5':
        return '0011'
    return '0010'


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("ffpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '219.135.56.195'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('transCode', '001'),
        ('service', _get_pay_type(service)),
        ('customerNo', app_id),
        ('externalId', str(pay.id)),
        ('transAmount', int(pay_amount * 100)),
        ('reqDate', tz.local_now().strftime('%Y%m%d')),
        ('reqTime', tz.local_now().strftime('%H%M%S')),
        ('bgReturnUrl', '{}/pay/api/{}/miaofupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('requestIp', _get_device_ip(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("miaofupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['externalId'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("miaofupay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)
    template_data = {'base64_img': make_code(data['payUrl']), 'amount': pay_amount}
    t = get_template('qr_alipay_miaofu.html')
    html = t.render(Context(template_data))
    cache_id = redis_cache.save_html(pay.id, html)
    _LOGGER.info("miaofupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("miaofupay notify data: %s, order_id is: %s", data, data['externalId'])
    verify_notify_sign(data, api_key)
    pay_id = data['externalId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('miaofupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['seqno']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,00-交易成功
    if trade_status == '00':
        _LOGGER.info('miaofupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('transCode', '002'),
        ('externalId', str(pay_id)),
        ('customerNo', app_id),
        ('reqDate', time.strftime("%Y%m%d", time.localtime())),
        ('requestIp', _get_production_ip(app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("miaofupay query data: %s, order_id: %s", json.dumps(parameter_dict), parameter_dict['externalId'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("miaofupay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['code'])
        trade_no = str(data['seqno'])
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 07：未付 00：交易成功 99：交易失败 11：接收失败
        if trade_status == '00':
            _LOGGER.info('miaofupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('miaofupay data error, status_code: %s', response.status_code)
